package com.example.za.account.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.example.za.account.R;
import com.example.za.account.activity.RecordActivity;
import com.example.za.account.adapter.IncomeSwipeAdapter;
import com.example.za.account.application.AccountApplication;
import com.example.za.account.dao.IncomeCatDao;
import com.example.za.account.dao.IncomeDao;
import com.example.za.account.dao.InvestDao;
import com.example.za.account.model.Income;
import com.example.za.account.model.IncomeCat;
import com.example.za.account.model.Invest;
import com.example.za.account.utils.Constant;
import com.example.za.account.utils.DateUtils;
import com.example.za.account.utils.ScreenUtils;
import com.example.za.account.utils.T;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class ShowIncomeFragment extends ListFragment {

    @BindView(android.R.id.list)
    SwipeMenuListView mListFinance;
    Unbinder unbinder;
    private IncomeDao mIncomeDao;
    private List<Income> mIncomes;
    private IncomeSwipeAdapter mIncomeSwipeAdapter;
    private onIncomeChangeListener mOnIncomeChangeListener;
    private int mType;
    private View rootView;

    public static ShowIncomeFragment getInstance(int type) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constant.TYPE_DATE, type);
        ShowIncomeFragment showIncomeFragment = new ShowIncomeFragment();
        showIncomeFragment.setArguments(bundle);
        return showIncomeFragment;
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof onIncomeChangeListener) {
            mOnIncomeChangeListener = (onIncomeChangeListener) activity;
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mType = getArguments().getInt(Constant.TYPE_DATE);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_finance, container, false);
            unbinder = ButterKnife.bind(this, rootView);
            mIncomeDao = new IncomeDao(getActivity());
            switch (mType) {
                case Constant.TYPE_TODAY:
                    mIncomes = mIncomeDao.getPeriodIncomes(DateUtils.getTodayStart(),
                            DateUtils.getTodayEnd(), AccountApplication.sUser.getmId());
                    mIncomeSwipeAdapter = new IncomeSwipeAdapter(getActivity(), mIncomes, true);
                    break;
                case Constant.TYPE_WEEK:
                    mIncomes = mIncomeDao.getPeriodIncomes(DateUtils.getWeekStart(),
                            DateUtils.getWeekEnd(), AccountApplication.sUser.getmId());
                    mIncomeSwipeAdapter = new IncomeSwipeAdapter(getActivity(), mIncomes, false);
                    break;
                case Constant.TYPE_MONTH:
                    mIncomes = mIncomeDao.getPeriodIncomes(DateUtils.getMonthStart(),
                            DateUtils.getMonthEnd(), AccountApplication.sUser.getmId());
                    mIncomeSwipeAdapter = new IncomeSwipeAdapter(getActivity(), mIncomes, false);
                    break;
                default:
                    break;
            }
        }

        setListAdapter(mIncomeSwipeAdapter);

        //创建菜单项，设置文字、图标、宽度、背景等属性
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                deleteItem.setWidth(ScreenUtils.dp2px(getActivity(), 80));
                deleteItem.setIcon(R.drawable.btn_delete);
                menu.addMenuItem(deleteItem);
            }
        };
        mListFinance.setMenuCreator(creator);
        //为菜单项设置点击监听事件
        mListFinance.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                //如果删除成功，刷新数据，重绘界面
                //如果类型是投资类型的，也要删除投资表中的数据
                IncomeCat incomeCat = new IncomeCatDao(getActivity()).findInvest();
                if (((Income) mIncomeSwipeAdapter.getItem(mIncomes.size()
                        - 1 - position)).getmCategory().getmName().equals(incomeCat.getmName())) {

                    Income incom = mIncomes.get(mIncomes.size() - 1 - position);
                    if (mIncomeDao.deleteIncome((Income) mIncomeSwipeAdapter.getItem(mIncomes.size()
                            - 1 - position))) {
                        InvestDao investDao = new InvestDao(getActivity());
                        List<Invest> list = investDao.existsInfo(incom.getmSecond());
                        investDao.deleteInvest(list.get(0));
                        T.showShort(getActivity(), getString(R.string.delete_succeed));
                        mIncomes.remove(mIncomes.size() - 1 - position);
                        mIncomeSwipeAdapter.setData(mIncomes);
                        invalidateUI();
                        EventBus.getDefault().post("income_deleted");
                    } else {
                        T.showShort(getActivity(), getString(R.string.delete_fail));
                    }
                } else {
                    if (mIncomeDao.deleteIncome((Income) mIncomeSwipeAdapter.getItem(mIncomes.size()
                            - 1 - position))) {
                        T.showShort(getActivity(), getString(R.string.delete_succeed));
                        mIncomes.remove(mIncomes.size() - 1 - position);
                        mIncomeSwipeAdapter.setData(mIncomes);
                        invalidateUI();
                        EventBus.getDefault().post("income_deleted");
                    } else {
                        T.showShort(getActivity(), getString(R.string.delete_fail));
                    }
                }
                return false;
            }
        });

        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;

    }

    private void invalidateUI() {
        if (mOnIncomeChangeListener != null) {
            float income = 0;
            switch (mType) {
                case Constant.TYPE_TODAY:
                    income = mIncomeDao.getPeriodSumIncome(DateUtils.getTodayStart(),
                            DateUtils.getTodayEnd(), AccountApplication.sUser.getmId());
                    break;
                case Constant.TYPE_WEEK:
                    income = mIncomeDao.getPeriodSumIncome(DateUtils.getWeekStart(),
                            DateUtils.getWeekEnd(), AccountApplication.sUser.getmId());
                    break;
                case Constant.TYPE_MONTH:
                    income = mIncomeDao.getPeriodSumIncome(DateUtils.getMonthStart(),
                            DateUtils.getMonthEnd(), AccountApplication.sUser.getmId());
                    break;
                default:
                    break;
            }
            mOnIncomeChangeListener.updateIncome(income);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshUI(String message) {
        if (TextUtils.equals(message, "income_updated") && mOnIncomeChangeListener != null) {
            switch (mType) {
                case Constant.TYPE_TODAY:
                    mIncomes = mIncomeDao.getPeriodIncomes(DateUtils.getTodayStart(),
                            DateUtils.getTodayEnd(), AccountApplication.sUser.getmId());
                    break;
                case Constant.TYPE_WEEK:
                    mIncomes = mIncomeDao.getPeriodIncomes(DateUtils.getWeekStart(),
                            DateUtils.getWeekEnd(), AccountApplication.sUser.getmId());
                    break;
                case Constant.TYPE_MONTH:
                    mIncomes = mIncomeDao.getPeriodIncomes(DateUtils.getMonthStart(),
                            DateUtils.getMonthEnd(), AccountApplication.sUser.getmId());
                    break;
                default:
                    break;
            }
            mIncomeSwipeAdapter.setData(mIncomes);
            invalidateUI();
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Income income = (Income) l.getItemAtPosition(mIncomes.size() - 1 - position);
        Intent intent = new Intent(getActivity(), RecordActivity.class);
        intent.putExtra(Constant.RECORD, income);
        startActivity(intent);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mOnIncomeChangeListener = null;
    }


    public interface onIncomeChangeListener {
        void updateIncome(float income);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

}
